package com.jamal2362.apktool.util;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import com.jamal2362.apktool.R;

public class TextUtil {
	public static final String MD5 = "MD5";
	public static final String SHA1 = "SHA-1";
	public static final String SHA256 = "SHA-256";
	public static final String CRC32 = "CRC32";

	public static void setClipboard(Context context, String text) {
		if (TextUtils.isEmpty(text)) {
			return;
		}
		ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		ClipData clip = ClipData.newPlainText("Copied Text", text);
		clipboard.setPrimaryClip(clip);
		TextUtil.st(context, context.getString(R.string.copy_success));
	}

	public static String readFromClipboard(Context context) {
		ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		if (clipboard.hasPrimaryClip()) {
			ClipDescription description = clipboard.getPrimaryClipDescription();
			ClipData data = clipboard.getPrimaryClip();
			if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
				return String.valueOf(data.getItemAt(0).getText());
		}
		return null;
	}

	public static void st(Context ctx, String text) {
		Toast.makeText(ctx, text, Toast.LENGTH_SHORT).show();
	}

	public static String dateFormat(long ms) {
		Date date = new Date(ms);
		DateFormat formatter = new SimpleDateFormat(Settings.dateFormat);
		return formatter.format(date);
	}

	public static void setTextAppearance(Context context, TextView view, int resId) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
			view.setTextAppearance(context, resId);
		} else {
			view.setTextAppearance(resId);
		}
	}

	public static String replaceIllegal(String str) {
		return str.replaceAll("[\\\\/:*?\"<>|]", "_");
	}

	public static String encryptString(String str, String md) {
		String digest = null;
		try {
			MessageDigest crypt = MessageDigest.getInstance(md);
			crypt.reset();
			crypt.update(str.getBytes("UTF-8"));
			digest = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return digest.toLowerCase();
	}

	public static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}
}
